<template>
  <a-modal :width="700" v-model:visible="showAddMarketDialog" title="添加店铺" :footer="false" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <div class="add-shop-wrap">
      <a-steps :current="currentStep" style="margin-bottom: 30px">
        <a-step>添加站点</a-step>
        <a-step>广告授权</a-step>
      </a-steps>
      <div class="add-shop-con">
        <a-form style="width: 500px" :model="shopInfo">
          <a-form-item field="shopName" label="店铺名称">
            <a-input v-model="shopInfo.shopName" placeholder="请输入店铺名称" disabled />
          </a-form-item>
          <a-form-item label="店长">
            <a-input v-model="shopInfo.shopMasters" placeholder="请输入店铺名称" disabled />
          </a-form-item>
          <a-form-item field="region" label="区域">
            <a-select v-model="shopInfo.region" disabled>
              <a-option value="北美地区" label="北美地区" />
              <a-option value="欧洲地区" label="欧洲地区" />
              <a-option value="远东地区" label="远东地区" />
            </a-select>
          </a-form-item>
          <a-form-item field="marketplaceIds" v-if="currentStep == 1">
            <template #label>
              <span class="warningColor">*</span>
              <span>站点：</span>
            </template>
            <a-checkbox-group v-model="shopInfo.marketplaceIds">
              <a-checkbox :value="market.marketplaceId" v-for="market in marketList" :key="market.marketplaceId" :disabled="isDisabled(market.marketplaceId)">{{ market.marketplaceName }}</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
        </a-form>
        <a-table v-if="currentStep == 2" class="table-singe-line" size="mini" :columns="tableColumns" :pagination="false" :bordered="false" :data="shopMarketList" style="margin-top: 20px">
          <template #marketplaceId="{ record }">
            <p>{{ record.marketplaceName }}({{ record.marketplaceCode }})</p>
          </template>
          <template #shopClerks="{ record }">
            <a-select v-model="record.shopClerks" multiple allow-clear style="width: 300px">
              <a-option v-for="(item, index) in userList" :key="index" :value="item.id" :label="item.userName" />
            </a-select>
          </template>
          <template #baseAuthMap="{ record }">
            <div class="flex-c" style="width: 100px">
              <CopyText :val="adAuthUrlMap[record.marketplaceId]">
                <template #copyCon>
                  <p class="highlight cursor">复制链接去授权</p>
                </template>
              </CopyText>
            </div>
          </template>
        </a-table>
      </div>
      <div class="flex-c-end">
        <a-space>
          <a-button size="small" @click="closedDialog" v-if="currentStep == 1">取消</a-button>
          <a-button type="primary" size="small" @click="submitShop" :loading="summitLoading" v-if="currentStep == 1">保存并下一步</a-button>
          <a-button type="primary" size="small" @click="submitUser" :loading="summitLoading" v-if="currentStep == 2">保存</a-button>
        </a-space>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { getOrganizesUser, getShopMarketByRegion, createShopMarketBatch, getShopInfo, getAmazonAdAuthUrl, updateShopMarkets } from '@/api/system'
  import { Message } from '@arco-design/web-vue'
  onMounted(async () => {
    setShopInfo()
    getUserList()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    shops: {
      type: Object,
      default: () => {},
    },
  })

  const currentStep = ref(1)
  const showAddMarketDialog = ref(props.isShow)
  const shopInfo = ref<any>(props.shops)
  const tableColumns: Array<any> = [
    {
      title: '站点',
      dataIndex: 'marketplaceId',
      slotName: 'marketplaceId',
    },
    {
      title: '币种',
      dataIndex: 'currency',
      slotName: 'currency',
    },
    {
      title: '店员',
      dataIndex: 'shopClerks',
      slotName: 'shopClerks',
    },
    {
      title: '广告授权',
      dataIndex: 'baseAuthMap',
      slotName: 'baseAuthMap',
    },
  ]
  const userList = ref<Array<any>>([])
  const marketList = ref<Array<any>>([])
  const shopMarketList = ref<Array<any>>([])
  const adAuthUrlMap = ref<any>({})
  const summitLoading = ref(false)
  let defaultMarket = []

  function setShopInfo() {
    shopInfo.value = JSON.parse(JSON.stringify(props.shops)) || {}
    shopInfo.value.shopMasters = shopInfo.value.shopMasters?.[0]?.userName
    defaultMarket = shopInfo.value.shopMarkets?.map((el) => el.marketplaceId)
    shopInfo.value.marketplaceIds = [...defaultMarket]
    getMarketsByRegion()
  }
  function isDisabled(marketplaceId) {
    return defaultMarket.indexOf(marketplaceId) > -1
  }

  // 根据区域获取站点
  async function getMarketsByRegion() {
    const res: any = await getShopMarketByRegion({ region: shopInfo.value.region })
    marketList.value = res?.data || []
  }
  // 获取所有用户列表
  async function getUserList() {
    const res: any = await getOrganizesUser({
      pageNum: 1,
      pageSize: 1000,
    })
    userList.value = res?.data?.records || []
  }

  // 检测隐私授权状态
  async function getShopDetail() {
    const res: any = await getShopInfo({ id: shopInfo.value.id })
    if (!res) return
    shopMarketList.value = res.data?.shopMarkets || []
    shopMarketList.value.forEach((el: any) => {
      el.shopClerks = el.shopClerks.map((item: any) => item.userId)
    })
    let marketplaceIds = shopMarketList.value.map((el) => el.marketplaceId)
    const authUrlRes: any = await getAmazonAdAuthUrl({ marketplaceIds: marketplaceIds?.join(',') })
    adAuthUrlMap.value = authUrlRes?.data || {}
  }
  // 关闭
  function closedDialog() {
    if (currentStep.value == 1) {
      emit('closed')
    } else {
      emit('success')
    }
    showAddMarketDialog.value = false
  }
  // 提交店铺信息
  async function submitShop() {
    let addArr = shopInfo.value.marketplaceIds.filter(function (v) {
      return defaultMarket.indexOf(v) == -1
    })
    if (!addArr?.length) {
      return Message.error('请选择站点')
    }

    let marketItemParams = addArr.map((id) => {
      return {
        marketplaceId: id,
        shopClerkIds: [],
      }
    })
    summitLoading.value = true
    const res: any = await createShopMarketBatch({
      marketItemParams: marketItemParams,
      shopId: shopInfo.value.id,
    })
    summitLoading.value = false
    if (!res) return
    currentStep.value = 2
    getShopDetail()
  }
  // 批量修改站点信息
  async function submitUser() {
    let shopMarketItems = shopMarketList.value.map((el) => {
      return {
        id: el.id,
        shopClerkIds: el.shopClerks,
        clerkType: 2,
      }
    })
    summitLoading.value = true
    const res: any = await updateShopMarkets({ shopMarketItems: shopMarketItems })
    summitLoading.value = false
    if (res) {
      Message.success('保存成功！')
      closedDialog()
    }
  }
</script>
<style lang="less" scoped>
  .add-shop-wrap {
    padding: 0 20px;
    .add-shop-con {
      min-height: 400px;
      margin-bottom: 20px;
    }
  }
  .auth-w {
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid var(--color-border);
    line-height: 20px;
    .auth-url {
      margin-top: 20px;
    }
  }
  .arco-typography {
    margin-bottom: 0;
  }
  :deep(.arco-icon-check) {
    color: #fff;
  }
</style>
